"""
JH子系统 API路由
提供职位数据可视化相关的API接口
"""

from fastapi import APIRouter, HTTPException, Query, Depends, File, UploadFile, Form
from typing import Dict, List, Any, Optional
from pydantic import BaseModel
import io
import PyPDF2
import docx
from bs4 import BeautifulSoup

from ....jh_subsystem.job_data_service import job_data_service, JobDataFilters
from ...llm_api_service import LLMApiService

router = APIRouter(prefix="/jh", tags=["JH职位数据分析"])

# 复用大模型客户端（按需懒加载）
_llm_service: Optional[LLMApiService] = None

class JobSearchRequest(BaseModel):
    """职位搜索请求"""
    query: Optional[str] = None
    job_type: Optional[str] = None
    location: Optional[str] = None
    country: Optional[str] = None
    schedule_type: Optional[str] = None
    work_from_home: Optional[bool] = None
    salary_min: Optional[float] = None
    salary_max: Optional[float] = None
    page: int = 1
    page_size: int = 20

class ManualResumeInput(BaseModel):
    """手动输入简历信息"""
    name: str
    email: Optional[str] = None
    phone: Optional[str] = None
    education: Optional[str] = None
    experience: Optional[str] = None
    skills: List[str] = []
    summary: Optional[str] = None
    target_position: Optional[str] = None
    expected_salary: Optional[str] = None

class JobAnalysisRequest(BaseModel):
    """职位AI分析请求"""
    job_data: Dict[str, Any]
    user_profile: Optional[Dict[str, Any]] = None
    analysis_sections: List[str] = []  # ["basic_info", "skills", "benefits", "location", "source"]

class JobAnalysisResponse(BaseModel):
    """职位AI分析响应"""
    basic_info_analysis: Optional[str] = None
    skills_analysis: Optional[str] = None
    benefits_analysis: Optional[str] = None
    location_analysis: Optional[str] = None
    source_analysis: Optional[str] = None
    overall_recommendation: Optional[str] = None

class ResumeAnalysisResult(BaseModel):
    """简历分析结果"""
    skill_matches: Dict[str, float]
    competitiveness_score: float
    skill_match_score: float
    salary_competitiveness: float
    career_suggestions: List[str]
    recommended_positions: List[Dict[str, Any]]
    missing_skills: List[str]
    strength_areas: List[str]

@router.on_event("startup")
async def startup_event():
    """启动时初始化数据库"""
    try:
        await job_data_service.initialize_database()
    except Exception as e:
        print(f"JH子系统数据库初始化失败: {e}")

@router.get("/overview")
async def get_overview_statistics():
    """获取概览统计信息"""
    try:
        stats = await job_data_service.get_overview_statistics()
        return stats
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取统计信息失败: {str(e)}")

@router.get("/jobs")
async def get_jobs_paginated(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页大小"),
    job_type: Optional[str] = Query(None, description="职位类型"),
    location: Optional[str] = Query(None, description="工作地点"),
    country: Optional[str] = Query(None, description="国家"),
    schedule_type: Optional[str] = Query(None, description="工作类型"),
    work_from_home: Optional[bool] = Query(None, description="是否远程"),
    search_query: Optional[str] = Query(None, description="搜索关键词"),
    salary_min: Optional[float] = Query(None, description="最低薪资"),
    salary_max: Optional[float] = Query(None, description="最高薪资")
):
    """获取分页职位数据"""
    try:
        filters = JobDataFilters(
            job_type=job_type,
            location=location,
            country=country,
            schedule_type=schedule_type,
            work_from_home=work_from_home,
            search_query=search_query,
            salary_min=salary_min,
            salary_max=salary_max
        )
        
        result = await job_data_service.get_jobs_paginated(
            page=page,
            page_size=page_size,
            filters=filters
        )
        
        return result
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取职位数据失败: {str(e)}")

@router.get("/chart-data/{chart_type}")
async def get_chart_data(chart_type: str):
    """获取图表数据"""
    valid_chart_types = [
        "job_type_distribution",
        "location_distribution", 
        "salary_distribution",
        "time_trend",
        "skills_analysis",
        "company_ranking"
    ]
    
    if chart_type not in valid_chart_types:
        raise HTTPException(
            status_code=400, 
            detail=f"无效的图表类型。支持的类型: {', '.join(valid_chart_types)}"
        )
    
    try:
        data = await job_data_service.get_chart_data(chart_type)
        return data
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取图表数据失败: {str(e)}")

@router.get("/search")
async def search_jobs(
    query: str = Query(..., description="搜索关键词"),
    limit: int = Query(50, ge=1, le=100, description="结果数量限制")
):
    """搜索职位"""
    try:
        jobs = await job_data_service.search_jobs(query, limit)
        return {"jobs": jobs, "total": len(jobs)}
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"搜索职位失败: {str(e)}")

@router.post("/jobs/search")
async def advanced_search_jobs(request: JobSearchRequest):
    """高级职位搜索"""
    try:
        filters = JobDataFilters(
            job_type=request.job_type,
            location=request.location,
            country=request.country,
            schedule_type=request.schedule_type,
            work_from_home=request.work_from_home,
            search_query=request.query,
            salary_min=request.salary_min,
            salary_max=request.salary_max
        )
        
        result = await job_data_service.get_jobs_paginated(
            page=request.page,
            page_size=request.page_size,
            filters=filters
        )
        
        return result
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"高级搜索失败: {str(e)}")

@router.post("/resume/upload")
async def upload_resume(file: UploadFile = File(...)):
    """上传简历文件进行分析"""
    try:
        # 检查文件类型
        allowed_types = ['application/pdf', 'application/msword', 
                        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                        'text/html', 'text/plain']
        
        if file.content_type not in allowed_types:
            raise HTTPException(
                status_code=400, 
                detail=f"不支持的文件类型: {file.content_type}。支持的类型: PDF, DOC, DOCX, HTML, TXT"
            )
        
        # 读取文件内容
        content = await file.read()
        text_content = ""
        
        # 根据文件类型解析内容
        if file.content_type == 'application/pdf':
            text_content = extract_text_from_pdf(content)
        elif file.content_type in ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']:
            text_content = extract_text_from_docx(content)
        elif file.content_type == 'text/html':
            text_content = extract_text_from_html(content)
        else:
            text_content = content.decode('utf-8')
        
        # 分析简历内容
        analysis_result = await analyze_resume_content(text_content)
        
        return {
            "filename": file.filename,
            "content_type": file.content_type,
            "file_size": len(content),
            "extracted_text_length": len(text_content),
            "analysis": analysis_result
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"简历分析失败: {str(e)}")

@router.post("/resume/manual")
async def analyze_manual_resume(resume_data: ManualResumeInput):
    """分析手动输入的简历信息"""
    try:
        # 构建文本内容
        text_content = f"""
        姓名: {resume_data.name}
        邮箱: {resume_data.email or ''}
        电话: {resume_data.phone or ''}
        教育背景: {resume_data.education or ''}
        工作经验: {resume_data.experience or ''}
        技能: {', '.join(resume_data.skills)}
        个人简介: {resume_data.summary or ''}
        目标职位: {resume_data.target_position or ''}
        期望薪资: {resume_data.expected_salary or ''}
        """
        
        # 分析简历内容
        analysis_result = await analyze_resume_content(text_content)
        
        return {
            "input_type": "manual",
            "analysis": analysis_result
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"简历分析失败: {str(e)}")

@router.get("/resume/skills-benchmark")
async def get_skills_benchmark():
    """获取技能基准数据"""
    try:
        # 获取市场热门技能数据（与job_data_service一致的返回结构：labels/values）
        chart_data = await job_data_service.get_chart_data("skillsChart", limit=30)
        
        skills_benchmark = {}
        labels = chart_data.get("labels", [])
        values = chart_data.get("values", [])
        total = sum(values) if values else 1
        
        for i, skill in enumerate(labels):
            demand = values[i] if i < len(values) else 0
            demand_score = round(demand / total * 100, 2) if total else 0
            skills_benchmark[skill] = {
                "demand_score": demand_score,
                "avg_salary": 80000 + (i * 5000),  # 简单模拟薪资
                "growth_trend": "high" if i < 5 else ("medium" if i < 15 else "low")
                        }
        
        return {
            "skills_benchmark": skills_benchmark,
            "market_trends": {
                "hot_skills": labels[:5],
                "emerging_skills": labels[5:10] if len(labels) > 10 else labels[5:],
                "declining_skills": labels[-5:][::-1] if len(labels) >= 5 else []
            }
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取技能基准失败: {str(e)}")

@router.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy", "service": "JH职位数据分析服务"} 

def extract_text_from_pdf(content: bytes) -> str:
    """从PDF文件提取文本"""
    try:
        pdf_file = io.BytesIO(content)
        pdf_reader = PyPDF2.PdfReader(pdf_file)
        text = ""
        for page in pdf_reader.pages:
            text += page.extract_text() + "\n"
        return text.strip()
    except Exception as e:
        raise Exception(f"PDF解析失败: {str(e)}")

def extract_text_from_docx(content: bytes) -> str:
    """从DOCX文件提取文本"""
    try:
        doc_file = io.BytesIO(content)
        doc = docx.Document(doc_file)
        text = ""
        for paragraph in doc.paragraphs:
            text += paragraph.text + "\n"
        return text.strip()
    except Exception as e:
        raise Exception(f"DOCX解析失败: {str(e)}")

def extract_text_from_html(content: bytes) -> str:
    """从HTML文件提取文本"""
    try:
        soup = BeautifulSoup(content, 'html.parser')
        # 移除script和style标签
        for script in soup(["script", "style"]):
            script.decompose()
        return soup.get_text().strip()
    except Exception as e:
        raise Exception(f"HTML解析失败: {str(e)}")

async def analyze_resume_content(text_content: str) -> ResumeAnalysisResult:
    """分析简历内容（优先调用大模型，失败则回退到启发式）"""
    # 1) 优先：尝试大模型结构化输出
    try:
        llm_result = await _analyze_with_llm(text_content)
        if llm_result:
            return ResumeAnalysisResult(**llm_result)
    except Exception:
        # 忽略并回退
        pass

    # 2) 回退：启发式分析（原有实现）
    try:
        # 获取技能基准数据（与job_data_service的命名保持一致）
        chart_data = await job_data_service.get_chart_data("skillsChart")
        
        # 技能匹配分析
        skill_matches = analyze_skills_in_text(text_content, chart_data)
        
        # 计算竞争力分数
        competitiveness_score = calculate_competitiveness_score(skill_matches, text_content)
        # 修正：skill_match_score 取技能分数的平均值，已是 0-100 区间，不再额外乘以 100
        skill_match_score = sum(skill_matches.values()) / max(len(skill_matches), 1)
        salary_competitiveness = min(skill_match_score * 1.2, 100)
        
        # 生成职业建议
        career_suggestions = generate_career_suggestions(skill_matches, text_content)
        
        # 推荐职位
        recommended_positions = await get_recommended_positions(skill_matches)
        
        # 缺失技能和优势领域
        missing_skills = identify_missing_skills(skill_matches)
        strength_areas = identify_strength_areas(skill_matches)
        
        return ResumeAnalysisResult(
            skill_matches=skill_matches,
            competitiveness_score=competitiveness_score,
            skill_match_score=skill_match_score,
            salary_competitiveness=salary_competitiveness,
            career_suggestions=career_suggestions,
            recommended_positions=recommended_positions,
            missing_skills=missing_skills,
            strength_areas=strength_areas
        )
        
    except Exception as e:
        raise Exception(f"简历内容分析失败: {str(e)}")

def analyze_skills_in_text(text: str, chart_data: dict) -> Dict[str, float]:
    """分析文本中的技能匹配度"""
    skill_matches = {}
    text_lower = text.lower()
    
    # 预定义技能列表
    skills_list = [
        "python", "java", "javascript", "sql", "r", "scala", "c++", "c#",
        "machine learning", "deep learning", "data analysis", "statistics",
        "tensorflow", "pytorch", "scikit-learn", "pandas", "numpy",
        "hadoop", "spark", "kafka", "docker", "kubernetes",
        "aws", "azure", "gcp", "git", "linux", "excel"
    ]
    
    for skill in skills_list:
        # 简单的关键词匹配
        if skill.lower() in text_lower:
            # 计算匹配强度（基于出现次数和上下文）
            count = text_lower.count(skill.lower())
            base_score = min(count * 20, 80)  # 基础分数
            
            # 增加一些随机性使其更真实
            import random
            variation = random.uniform(0.8, 1.2)
            final_score = min(base_score * variation, 100)
            
            skill_matches[skill] = round(final_score, 1)
    
    return skill_matches

def calculate_competitiveness_score(skill_matches: Dict[str, float], text: str) -> float:
    """计算整体竞争力分数"""
    if not skill_matches:
        return 50.0
    
    # 基于技能匹配度计算
    avg_skill_score = sum(skill_matches.values()) / len(skill_matches)
    
    # 基于经验年限（简单解析）
    experience_bonus = 0
    if "年" in text or "year" in text.lower():
        experience_bonus = 10
    
    # 基于教育背景
    education_bonus = 0
    education_keywords = ["学士", "硕士", "博士", "bachelor", "master", "phd", "university", "college"]
    for keyword in education_keywords:
        if keyword in text.lower():
            education_bonus = 5
            break
    
    total_score = min(avg_skill_score + experience_bonus + education_bonus, 100)
    return round(total_score, 1)

def generate_career_suggestions(skill_matches: Dict[str, float], text: str) -> List[str]:
    """生成职业发展建议"""
    suggestions = []
    
    # 基于技能强弱给出建议
    strong_skills = [skill for skill, score in skill_matches.items() if score > 70]
    weak_skills = [skill for skill, score in skill_matches.items() if score < 50]
    
    if strong_skills:
        suggestions.append(f"您在 {', '.join(strong_skills[:3])} 方面表现突出，建议继续深化这些技能")
    
    if weak_skills:
        suggestions.append(f"建议加强 {', '.join(weak_skills[:3])} 相关技能的学习")
    
    # 通用建议
    suggestions.extend([
        "考虑获得相关技术认证来提升竞争力",
        "建议参与开源项目来展示实际技能",
        "定期更新技能以跟上行业发展趋势",
        "考虑建立个人技术博客或作品集"
    ])
    
    return suggestions

async def get_recommended_positions(skill_matches: Dict[str, float]) -> List[Dict[str, Any]]:
    """获取推荐职位（按匹配度降序，附带推荐原因与必要字段）"""
    try:
        jobs_data = await job_data_service.get_jobs_paginated(page=1, page_size=50)
        user_skill_scores = {str(k).lower(): float(v) for k, v in (skill_matches or {}).items()}
        recommendations: List[Dict[str, Any]] = []

        for job in jobs_data.get('jobs', []) or []:
            job_skills = job.get('job_skills') or []
            skills_original = job_skills if isinstance(job_skills, list) else []
            skills_lower = [s.strip().lower() for s in skills_original if isinstance(s, str) and s.strip()]
            matched_lower = [s for s in skills_lower if s in user_skill_scores]

            if matched_lower:
                scores = [user_skill_scores[s] for s in matched_lower]
                match_score = sum(scores) / len(scores)
            else:
                match_score = 0.0

            # 推荐原因：展示前3个匹配技能
            matched_original_order = [s for s in skills_original if isinstance(s, str) and s.strip().lower() in set(matched_lower)]
            top3 = matched_original_order[:3]
            reasons = [f"技能匹配: {', '.join(top3)}"] if top3 else []

            recommendations.append({
                "id": job.get("id"),
                "title": job.get('job_title_short', '') or job.get('job_title', ''),
                "company": job.get('company_name', ''),
                "location": job.get('job_location', ''),
                "match_score": round(float(match_score), 1),
                "salary_range": f"${job.get('salary_year_avg', 0):,.0f}" if job.get('salary_year_avg') else "待议",
                "tags": skills_original[:4] if isinstance(skills_original, list) else [],
                "type": job.get('job_schedule_type', '') or '全职',
                "posted_at": job.get('job_posted_date_formatted') or job.get('job_posted_date') or '',
                "match_reasons": reasons,
            })

        recommendations.sort(key=lambda x: x.get('match_score') or 0, reverse=True)
        return recommendations[:20]
    except Exception:
        return []

def identify_missing_skills(skill_matches: Dict[str, float]) -> List[str]:
    """识别缺失的重要技能"""
    important_skills = ["Python", "SQL", "Machine Learning", "Data Analysis", "Git", "Docker"]
    missing = [skill for skill in important_skills if skill.lower() not in [s.lower() for s in skill_matches.keys()]]
    return missing[:5]  # 返回前5个

def identify_strength_areas(skill_matches: Dict[str, float]) -> List[str]:
    """识别优势领域"""
    strength_areas = []
    strong_skills = [skill for skill, score in skill_matches.items() if score > 70]
    
    # 按技能分类
    if any(skill in strong_skills for skill in ["python", "java", "javascript", "c++"]):
        strength_areas.append("编程开发")
    
    if any(skill in strong_skills for skill in ["machine learning", "deep learning", "tensorflow"]):
        strength_areas.append("机器学习")
        
    if any(skill in strong_skills for skill in ["data analysis", "statistics", "sql"]):
        strength_areas.append("数据分析")
    
    if any(skill in strong_skills for skill in ["aws", "azure", "docker", "kubernetes"]):
        strength_areas.append("云计算与DevOps")
    
    return strength_areas 

def _parse_structured_json(text: str) -> Dict[str, Any]:
    """尽力从模型输出中提取严格JSON并解析。失败返回空dict"""
    import json
    content = (text or "").strip()
    if not content:
        return {}
    try:
        return json.loads(content)
    except Exception:
        pass
    start = content.find("{")
    end = content.rfind("}")
    if start != -1 and end != -1 and end > start:
        snippet = content[start:end+1]
        try:
            return json.loads(snippet)
        except Exception:
            pass
    try:
        return json.loads(content.replace("'", '"'))
    except Exception:
        return {}

async def _analyze_with_llm(text_content: str) -> Optional[Dict[str, Any]]:
    """调用大模型进行简历结构化分析，返回与 ResumeAnalysisResult 字段兼容的 dict"""
    global _llm_service
    if _llm_service is None:
        _llm_service = LLMApiService()

    system_prompt = (
        "你是资深的简历分析专家。请基于用户提供的完整简历文本，进行结构化分析，并只输出JSON。不输出任何解释或前后缀。"
        "JSON 字段规范如下：\n"
        "{\n"
        "  \"skill_matches\": {\"<skill>\": <0-100分>},\n"
        "  \"competitiveness_score\": <0-100的数字>,\n"
        "  \"skill_match_score\": <0-100的数字>,\n"
        "  \"salary_competitiveness\": <0-100的数字>,\n"
        "  \"career_suggestions\": [\"建议1\", \"建议2\"],\n"
        "  \"missing_skills\": [\"技能A\", \"技能B\"],\n"
        "  \"strength_areas\": [\"领域A\", \"领域B\"]\n"
        "}"
    )
    user_prompt = (
        "请分析以下简历全文，识别关键技能并评分（0-100，越高越强），综合生成竞争力分、技能匹配分、薪资竞争力，列出缺失技能、优势领域与可执行的职业建议。\n\n"
        f"简历全文：\n{text_content}"
    )

    resp = await _llm_service.chat_completion(
        messages=[{"role": "user", "content": user_prompt}],
        system_prompt=system_prompt,
        temperature=0.2,
        max_tokens=1200,
    )
    content = (resp or {}).get("message", {}).get("content", "")
    data = _parse_structured_json(content)
    if not isinstance(data, dict) or not data:
        return None

    # 字段兜底与裁剪
    skill_matches = data.get("skill_matches") or {}
    try:
        skill_matches = {k: float(v) for k, v in skill_matches.items()}
    except Exception:
        skill_matches = {}

    # 如果缺少匹配分，按启发式补齐
    skill_match_score = data.get("skill_match_score")
    if skill_match_score is None:
        skill_match_score = (sum(skill_matches.values()) / max(len(skill_matches), 1)) if skill_matches else 0.0

    salary_competitiveness = data.get("salary_competitiveness")
    if salary_competitiveness is None:
        salary_competitiveness = min(float(skill_match_score) * 1.2, 100)

    competitiveness_score = float(data.get("competitiveness_score") or 0.0)
    career_suggestions = data.get("career_suggestions") or []
    missing_skills = data.get("missing_skills") or []
    strength_areas = data.get("strength_areas") or []

    # 保持前端兼容：推荐职位基于内部岗位数据
    recommended_positions = await get_recommended_positions(skill_matches)

    return {
        "skill_matches": skill_matches,
        "competitiveness_score": round(float(competitiveness_score), 1),
        "skill_match_score": round(float(skill_match_score), 1),
        "salary_competitiveness": round(float(salary_competitiveness), 1),
        "career_suggestions": list(career_suggestions)[:8],
        "recommended_positions": recommended_positions,
        "missing_skills": list(missing_skills)[:5],
        "strength_areas": list(strength_areas)[:5],
    }

@router.post("/analyze/job", response_model=JobAnalysisResponse)
async def analyze_job_position(request: JobAnalysisRequest):
    """
    AI分析职位信息，为每个模块生成个性化分析
    """
    try:
        global _llm_service
        if _llm_service is None:
            _llm_service = LLMApiService()
    except:
        # 如果LLM服务不可用，返回默认分析
        return _get_default_analysis(request)
    
    job = request.job_data
    user_profile = request.user_profile or {}
    sections = request.analysis_sections or ["basic_info", "skills", "benefits", "location", "source"]
    
    # 构建职位基本信息
    job_title = job.get('job_title') or job.get('job_title_short', '未知职位')
    company_name = job.get('company_name', '未知公司')
    location = job.get('job_location', '未指定')
    salary = job.get('salary_year_avg')
    work_from_home = job.get('job_work_from_home', 0) == 1
    health_insurance = job.get('job_health_insurance', 0) == 1
    no_degree = job.get('job_no_degree_mention', 0) == 1
    schedule_type = job.get('job_schedule_type', '未指定')
    job_via = job.get('job_via', '未知')
    
    # 技能信息
    skills = []
    if job.get('job_skills'):
        try:
            if isinstance(job['job_skills'], list):
                skills = job['job_skills']
            else:
                skills = str(job['job_skills']).split(',')
            skills = [s.strip() for s in skills if s.strip()]
        except:
            skills = []
    
    # 用户简历技能
    user_skills = user_profile.get('skill_matches', {})
    user_experience = user_profile.get('experience_years', 0)
    
    results = {}
    
    # 基本信息分析
    if "basic_info" in sections:
        try:
            analysis = await _analyze_basic_info(job_title, salary, work_from_home, health_insurance, schedule_type, user_experience)
            results["basic_info_analysis"] = analysis
        except Exception as e:
            results["basic_info_analysis"] = f"该职位提供了相对均衡的薪酬福利组合，{schedule_type}模式{'支持远程' if work_from_home else '需现场办公'}，整体具有一定吸引力。"
    
    # 技能要求分析
    if "skills" in sections and skills:
        try:
            analysis = await _analyze_skills(skills, user_skills)
            results["skills_analysis"] = analysis
        except Exception as e:
            results["skills_analysis"] = f"该职位需要{len(skills)}项关键技能，建议重点关注{'、'.join(skills[:3])}等核心技术，并根据自身情况有针对性地提升。"
    
    # 福利待遇分析
    if "benefits" in sections:
        try:
            analysis = await _analyze_benefits(work_from_home, health_insurance, no_degree, salary, schedule_type)
            results["benefits_analysis"] = analysis
        except Exception as e:
            benefits_count = sum([work_from_home, health_insurance, no_degree, bool(salary)])
            results["benefits_analysis"] = f"该职位提供{benefits_count}项福利待遇，体现了企业{'较好' if benefits_count >= 3 else '基础'}的员工关怀程度。"
    
    # 地理位置分析
    if "location" in sections:
        try:
            analysis = await _analyze_location(location, work_from_home)
            results["location_analysis"] = analysis
        except Exception as e:
            results["location_analysis"] = f"工作地点位于{location}，{'支持远程办公' if work_from_home else '需要现场办公'}，需要考虑通勤便利性。"
    
    # 招聘来源分析
    if "source" in sections:
        try:
            analysis = await _analyze_source(job_via)
            results["source_analysis"] = analysis
        except Exception as e:
            results["source_analysis"] = f"通过{job_via}发布，{'属于主流' if job_via.lower() in ['linkedin', 'indeed', 'glassdoor'] else '需要进一步'}验证招聘信息的真实性。"
    
    return JobAnalysisResponse(**results)

def _get_default_analysis(request: JobAnalysisRequest) -> JobAnalysisResponse:
    """获取默认分析（当LLM不可用时）"""
    job = request.job_data
    sections = request.analysis_sections or ["basic_info", "skills", "benefits", "location", "source"]
    
    results = {}
    
    if "basic_info" in sections:
        results["basic_info_analysis"] = "该职位提供了相对均衡的薪酬福利组合，工作模式较为灵活，整体具有一定吸引力。"
    
    if "skills" in sections:
        results["skills_analysis"] = "该职位技能要求合理，建议重点关注核心技术栈，并根据自身情况有针对性地提升相关技能。"
    
    if "benefits" in sections:
        results["benefits_analysis"] = "该职位提供的福利待遇较为完整，体现了企业对员工的关怀，有助于工作生活平衡。"
    
    if "location" in sections:
        results["location_analysis"] = "该地理位置为职业发展提供了良好的环境，需要结合个人情况考虑通勤和生活成本。"
    
    if "source" in sections:
        results["source_analysis"] = "该招聘渠道具有一定可信度，建议在申请前进一步验证职位和企业信息。"
    
    return JobAnalysisResponse(**results)

async def _analyze_basic_info(job_title: str, salary: float, work_from_home: bool, health_insurance: bool, schedule_type: str, user_experience: int) -> str:
    """分析基本信息"""
    global _llm_service
    
    prompt = f"""分析这个职位的基本信息，50字以内：

职位：{job_title}
薪资：{f'${salary:,.0f}/年' if salary else '面议'}
远程工作：{'支持' if work_from_home else '不支持'}
医疗保险：{'提供' if health_insurance else '不提供'}
工作类型：{schedule_type}
求职者经验：{user_experience}年

请从薪资竞争力、工作灵活性、福利完善度角度简要分析，直接输出分析文字。"""
    
    response = await _llm_service.chat_completion(
        messages=[{"role": "user", "content": prompt}],
        system_prompt="你是资深的职业顾问，擅长分析职位信息。请提供简洁、专业的分析意见。",
        temperature=0.3,
        max_tokens=200
    )
    
    return response.get("message", {}).get("content", "").strip()

async def _analyze_skills(skills: list, user_skills: dict) -> str:
    """分析技能要求"""
    global _llm_service
    
    # 计算技能匹配情况
    matched_skills = []
    missing_skills = []
    
    for skill in skills[:8]:
        skill_lower = skill.lower()
        if any(skill_lower in user_skill.lower() for user_skill in user_skills.keys()):
            user_score = max([score for user_skill, score in user_skills.items() 
                            if skill_lower in user_skill.lower()] + [0])
            matched_skills.append(f"{skill}({user_score:.0f}%)")
        else:
            missing_skills.append(skill)
    
    match_info = ""
    if matched_skills:
        match_info += f"匹配技能：{', '.join(matched_skills[:3])}；"
    if missing_skills:
        match_info += f"需要提升：{', '.join(missing_skills[:3])}；"
    
    prompt = f"""分析这个职位的技能要求，50字以内：

技能要求：{', '.join(skills[:8])}
{match_info}

请分析技能难度层次和匹配建议，直接输出分析文字。"""
    
    response = await _llm_service.chat_completion(
        messages=[{"role": "user", "content": prompt}],
        system_prompt="你是资深技术专家，擅长分析技能要求。请提供简洁、实用的建议。",
        temperature=0.3,
        max_tokens=200
    )
    
    return response.get("message", {}).get("content", "").strip()

async def _analyze_benefits(work_from_home: bool, health_insurance: bool, no_degree: bool, salary: float, schedule_type: str) -> str:
    """分析福利待遇"""
    global _llm_service
    
    benefits = []
    if work_from_home:
        benefits.append("远程工作")
    if health_insurance:
        benefits.append("医疗保险")
    if no_degree:
        benefits.append("无学历限制")
    if salary:
        benefits.append(f"年薪${salary:,.0f}")
    
    prompt = f"""分析这个职位的福利待遇，50字以内：

福利内容：{', '.join(benefits) if benefits else '基础福利'}
工作类型：{schedule_type}

请从福利竞争力和工作生活平衡角度分析，直接输出分析文字。"""
    
    response = await _llm_service.chat_completion(
        messages=[{"role": "user", "content": prompt}],
        system_prompt="你是HR专家，擅长分析员工福利。请提供专业的见解。",
        temperature=0.3,
        max_tokens=200
    )
    
    return response.get("message", {}).get("content", "").strip()

async def _analyze_location(location: str, work_from_home: bool) -> str:
    """分析地理位置"""
    global _llm_service
    
    prompt = f"""分析这个职位的地理位置优势，40字以内：

工作地点：{location}
远程工作：{'支持' if work_from_home else '仅现场办公'}

请分析地理位置的便利性和对职业发展的影响，直接输出分析文字。"""
    
    response = await _llm_service.chat_completion(
        messages=[{"role": "user", "content": prompt}],
        system_prompt="你是地区发展专家，擅长分析地理位置对职业的影响。",
        temperature=0.3,
        max_tokens=150
    )
    
    return response.get("message", {}).get("content", "").strip()

async def _analyze_source(job_via: str) -> str:
    """分析招聘来源"""
    global _llm_service
    
    prompt = f"""分析这个招聘来源的可信度，30字以内：

招聘来源：{job_via}

请分析平台权威性和职位真实性，直接输出分析文字。"""
    
    response = await _llm_service.chat_completion(
        messages=[{"role": "user", "content": prompt}],
        system_prompt="你是招聘行业专家，擅长评估招聘渠道。",
        temperature=0.3,
        max_tokens=120
    )
    
    return response.get("message", {}).get("content", "").strip() 